package com.nami.dispatcher.domain.handler.impl;


import cn.hutool.core.collection.CollUtil;
import com.nami.dispatcher.domain.gateway.UserGateway;
import com.nami.dispatcher.domain.handler.SendFailHandler;
import com.nami.dispatcher.domain.message.model.PacketTrans;
import com.nami.dispatcher.domain.middleware.mq.DomainEventPublisher;
import com.nami.gate.external.basic.cache.user.DeviceInfo;
import com.nami.gate.external.basic.cache.user.UserDeviceRel;
import com.nami.gate.external.basic.constants.DownTopicConst;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dromara.common.core.utils.SessionUtil;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述：
 *
 * @Author: lbc
 * @Date: 2023-08-18 9:15
 * @email: 594599620@qq.com
 * @Description: keep coding
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SendMsgFailHandlerImpl implements SendFailHandler {

    private final DomainEventPublisher publisher;

    private final UserGateway userCacheService;

    @Override
    public void handleFailSend(List<PacketTrans> transTask) {
        try {
            for (PacketTrans packetTransBO : transTask) {
//                log.info("[qos-fail] 准备移除用户[{}]在线状态.", packetTransBO.getIdentityNo());
                if (StringUtils.isBlank(packetTransBO.getSessionId())) {
                    log.error("[qos-fail] 结束假在线用户【{}】失败, 丢失参数identityNo", packetTransBO.getSessionId());
                    continue;
                }
                if (StringUtils.isBlank(packetTransBO.getAppKey())) {
                    log.error("[qos-fail] 结束假在线用户【{}】失败, 丢失参数appKey", packetTransBO.getSessionId());
                    continue;
                }

                UserDeviceRel userDTO = userCacheService.getOnlUserDetailInfoById(packetTransBO.getAppKey(),
                    SessionUtil.getUserId(packetTransBO.getSessionId()));

//                SingleResponse<UserWithDeviceInfoDTO> result = userCacheService.getUserInfoFromCacheOrDB();
//                if (!result.isSuccess()) {
//                    return;
//                }

                if (userDTO == null) {
                    log.warn("[qos-fail] 用户下线了。 appKey={}, userId={}", packetTransBO.getAppKey(), packetTransBO.getSessionId());
                    return;
                }

                List<DeviceInfo> devices = userDTO.getDeviceInfos();
                if (CollUtil.isEmpty(devices)) {
                    return;
                }
                String instanceId = SessionUtil.getInstanceId(packetTransBO.getSessionId());
                DeviceInfo deviceInfo = devices.stream()
                    .filter(item -> item != null && item.getInstanceId().equals(instanceId))
                    .collect(Collectors.toSet()).stream().findFirst().orElse(null);
                if (deviceInfo == null) {
                    return;
                }
//                UserDeviceDelCmd request = new UserDeviceDelCmd();
//                request.setAppKey(packetTransBO.getAppKey());
//                request.setUserId(IdentityUtil.getUserId(packetTransBO.getIdentityNo()));
//                request.setPlatform(IdentityUtil.getDeviceType(packetTransBO.getIdentityNo()));

                if (!userCacheService.removeOfflineDevice(packetTransBO.getAppKey(),
                    SessionUtil.getUserId(packetTransBO.getSessionId()),
                    SessionUtil.getInstanceId(packetTransBO.getSessionId()
                    ))) { // 返回true则为，删除了缓存数据。false代表 缓存就没有数据，没有执行删除操作
                    return;
                }
                // 关闭channel
                log.info("[qos-fail] 发送失败策略。关闭通道。sessionId=[{}]", packetTransBO.getSessionId());
                publisher.publish(DownTopicConst.CLOSE_CHANNEL_TOPIC, packetTransBO.getMqTags(), packetTransBO.getSessionId());

            }
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("[qos-fail] 移除用户在线状态发生异常. e:{}", e.getMessage());
        }

    }


}
